package org.lab.tracecash.services;

import java.util.List;

import javax.inject.Inject;
import javax.inject.Provider;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;

import org.lab.tracecash.model.Account;
import org.lab.tracecash.model.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class UserService {

	private static final Logger LOG = LoggerFactory.getLogger(UserService.class);

	@Inject
	private Provider<EntityManager> entityManagerProvider;

	public List<User> getAll() {
		return entityManagerProvider.get().createQuery("select a from User a order by a.id", User.class).getResultList();
	}

	public User findById(Long userId) {
		return entityManagerProvider.get().find(User.class, userId);
	}

	public User findByUserName(String name) {
		return entityManagerProvider.get().createQuery("select u from User u where u.name = :name", User.class).setParameter("name", name).getSingleResult();
	}

	public User findByEmail(String email) {
		try {
			return entityManagerProvider.get().createQuery("select u from User u where u.email = :email", User.class).setParameter("email", email).getSingleResult();
		} catch (NoResultException ex) {
			LOG.debug("Unknown email user: " + email);
			return null;
		}
	}

	public User findByName(String name) {
		return entityManagerProvider.get().createQuery("select u from User u where u.name = :name", User.class).setParameter("name", name).getSingleResult();
	}

	public List<Account> getUserAccounts(Long userId) {
		return entityManagerProvider.get().createQuery("select a from Account a where a.owner.id = :id order by a.name", Account.class).setParameter("id", userId).getResultList();
	}
}
